// 全局变量
let currentMode = 'single';
let currentSingleFile = null;
let currentBatchFiles = [];
let singleCompressedResult = null;
let batchCompressedResults = [];

// DOM元素
const elements = {
    // 模式切换
    navBtns: document.querySelectorAll('.nav-btn'),
    singleMode: document.getElementById('single-mode'),
    batchMode: document.getElementById('batch-mode'),

    // 单张压缩相关
    singleUpload: document.getElementById('single-upload'),
    singleFileInput: document.getElementById('single-file-input'),
    singleUploadBtn: document.querySelector('#single-upload .upload-btn'),
    optionsPanel: document.getElementById('options-panel'),
    qualitySlider: document.getElementById('quality'),
    qualityValue: document.querySelector('.quality-value'),
    presetBtns: document.querySelectorAll('.preset-btn'),
    formatSelect: document.getElementById('format'),
    singleCompressBtn: document.getElementById('single-compress-btn'),
    singleResult: document.getElementById('single-result'),
    singleDownloadBtn: document.getElementById('single-download-btn'),

    // 批量压缩相关
    batchUpload: document.getElementById('batch-upload'),
    batchFileInput: document.getElementById('batch-file-input'),
    batchUploadBtn: document.querySelector('#batch-upload .upload-btn'),
    batchOptions: document.getElementById('batch-options'),
    batchQuality: document.getElementById('batch-quality'),
    batchQualityValue: document.querySelector('#batch-options .quality-value'),
    batchFormat: document.getElementById('batch-format'),
    batchCompressBtn: document.getElementById('batch-compress-btn'),
    batchResults: document.getElementById('batch-results'),
    batchGrid: document.getElementById('batch-grid'),
    batchOriginalTotal: document.getElementById('batch-original-total'),
    batchCompressedTotal: document.getElementById('batch-compressed-total'),
    batchSaved: document.getElementById('batch-saved'),
    downloadAllBtn: document.getElementById('download-all-btn'),

    // 通用元素
    loadingOverlay: document.getElementById('loading-overlay'),
    toast: document.getElementById('toast')
};

// 初始化
document.addEventListener('DOMContentLoaded', function() {
    initEventListeners();
    setupDragAndDrop();
});

// 事件监听器初始化
function initEventListeners() {
    // 模式切换
    elements.navBtns.forEach(btn => {
        btn.addEventListener('click', () => switchMode(btn.dataset.mode));
    });

    // 单张压缩事件
    elements.singleUploadBtn.addEventListener('click', () => elements.singleFileInput.click());
    elements.singleFileInput.addEventListener('change', handleSingleFileSelect);
    elements.singleUpload.addEventListener('click', () => elements.singleFileInput.click());

    // 质量滑块
    elements.qualitySlider.addEventListener('input', (e) => {
        elements.qualityValue.textContent = e.target.value + '%';
        updatePresetButtons(e.target.value);
    });

    // 预设按钮
    elements.presetBtns.forEach(btn => {
        btn.addEventListener('click', () => {
            const quality = btn.dataset.quality;
            elements.qualitySlider.value = quality;
            elements.qualityValue.textContent = quality + '%';
            updatePresetButtons(quality);
        });
    });

    // 单张压缩按钮
    elements.singleCompressBtn.addEventListener('click', compressSingleImage);
    elements.singleDownloadBtn.addEventListener('click', downloadSingleImage);

  
    
    // 滑动对比功能
    initSliderComparison();

  
    // 批量压缩事件
    elements.batchUploadBtn.addEventListener('click', () => elements.batchFileInput.click());
    elements.batchFileInput.addEventListener('change', handleBatchFileSelect);
    elements.batchUpload.addEventListener('click', () => elements.batchFileInput.click());

    // 批量质量滑块
    elements.batchQuality.addEventListener('input', (e) => {
        elements.batchQualityValue.textContent = e.target.value + '%';
        updateBatchPresetButtons(e.target.value);
    });

    // 批量预设按钮
    const batchPresetBtns = document.querySelectorAll('#batch-options .preset-btn');
    batchPresetBtns.forEach(btn => {
        btn.addEventListener('click', () => {
            const quality = btn.dataset.quality;
            elements.batchQuality.value = quality;
            elements.batchQualityValue.textContent = quality + '%';
            updateBatchPresetButtons(quality);
        });
    });

    // 批量压缩按钮
    elements.batchCompressBtn.addEventListener('click', compressBatchImages);
    elements.downloadAllBtn.addEventListener('click', downloadAllImages);
}

// 模式切换
function switchMode(mode) {
    currentMode = mode;

    // 更新导航按钮状态
    elements.navBtns.forEach(btn => {
        btn.classList.toggle('active', btn.dataset.mode === mode);
    });

    // 更新模式显示
    elements.singleMode.classList.toggle('active', mode === 'single');
    elements.batchMode.classList.toggle('active', mode === 'batch');

    // 重置状态
    resetSingleMode();
    resetBatchMode();
}

// 重置单张模式
function resetSingleMode() {
    currentSingleFile = null;
    singleCompressedResult = null;
    elements.optionsPanel.style.display = 'none';
    elements.singleResult.style.display = 'none';
    elements.singleFileInput.value = '';
    updateSingleUploadContent();
}

// 重置批量模式
function resetBatchMode() {
    currentBatchFiles = [];
    batchCompressedResults = [];
    elements.batchOptions.style.display = 'none';
    elements.batchResults.style.display = 'none';
    elements.batchFileInput.value = '';
    elements.batchGrid.innerHTML = '';
    updateBatchUploadContent();
}

// 设置拖拽上传
function setupDragAndDrop() {
    // 单张上传拖拽
    elements.singleUpload.addEventListener('dragover', (e) => {
        e.preventDefault();
        elements.singleUpload.classList.add('dragover');
    });

    elements.singleUpload.addEventListener('dragleave', () => {
        elements.singleUpload.classList.remove('dragover');
    });

    elements.singleUpload.addEventListener('drop', (e) => {
        e.preventDefault();
        elements.singleUpload.classList.remove('dragover');

        const files = e.dataTransfer.files;
        if (files.length > 0) {
            handleSingleFile(files[0]);
        }
    });

    // 批量上传拖拽
    elements.batchUpload.addEventListener('dragover', (e) => {
        e.preventDefault();
        elements.batchUpload.classList.add('dragover');
    });

    elements.batchUpload.addEventListener('dragleave', () => {
        elements.batchUpload.classList.remove('dragover');
    });

    elements.batchUpload.addEventListener('drop', (e) => {
        e.preventDefault();
        elements.batchUpload.classList.remove('dragover');

        const files = Array.from(e.dataTransfer.files);
        if (files.length > 0) {
            handleBatchFiles(files);
        }
    });
}

// 处理单张文件选择
function handleSingleFileSelect(e) {
    const file = e.target.files[0];
    if (file) {
        handleSingleFile(file);
    }
}

// 处理单张文件
function handleSingleFile(file) {
    if (!validateImageFile(file)) {
        return;
    }

    currentSingleFile = file;
    updateSingleUploadContent();
    elements.optionsPanel.style.display = 'block';
    elements.singleResult.style.display = 'none';
}

// 更新单张上传内容
function updateSingleUploadContent() {
    const uploadContent = elements.singleUpload.querySelector('.upload-content');

    if (currentSingleFile) {
        uploadContent.innerHTML = `
            <i class="ri-image-2-line upload-icon"></i>
            <h3>${currentSingleFile.name}</h3>
            <p>大小: ${formatFileSize(currentSingleFile.size)}</p>
            <button class="upload-btn" onclick="document.getElementById('single-file-input').click()">重新选择</button>
        `;
    } else {
        uploadContent.innerHTML = `
            <i class="ri-upload-cloud-2-line upload-icon"></i>
            <h3>拖放图片到这里</h3>
            <p>或点击选择文件</p>
            <p class="file-types">支持格式：JPG、PNG、WebP、GIF（最大10MB）</p>
            <input type="file" id="single-file-input" accept="image/*" hidden>
            <button class="upload-btn">选择图片</button>
        `;

        // 重新绑定事件
        const newInput = document.getElementById('single-file-input');
        const newBtn = uploadContent.querySelector('.upload-btn');
        newBtn.addEventListener('click', () => newInput.click());
        newInput.addEventListener('change', handleSingleFileSelect);
    }
}

// 处理批量文件选择
function handleBatchFileSelect(e) {
    const files = Array.from(e.target.files);
    handleBatchFiles(files);
}

// 处理批量文件
function handleBatchFiles(files) {
    const validFiles = files.filter(file => validateImageFile(file));

    if (validFiles.length === 0) {
        showToast('没有有效的图片文件', 'error');
        return;
    }

    if (validFiles.length > 10) {
        showToast('最多只能同时处理10张图片', 'warning');
        validFiles.splice(10);
    }

    currentBatchFiles = validFiles;
    updateBatchUploadContent();
    elements.batchOptions.style.display = 'block';
    elements.batchResults.style.display = 'none';
}

// 更新批量上传内容
function updateBatchUploadContent() {
    const uploadContent = elements.batchUpload.querySelector('.upload-content');

    if (currentBatchFiles.length > 0) {
        const totalSize = currentBatchFiles.reduce((sum, file) => sum + file.size, 0);
        uploadContent.innerHTML = `
            <i class="ri-image-line upload-icon"></i>
            <h3>已选择 ${currentBatchFiles.length} 张图片</h3>
            <p>总大小: ${formatFileSize(totalSize)}</p>
            <div style="max-height: 100px; overflow-y: auto; margin: 1rem 0;">
                ${currentBatchFiles.map(file =>
                    `<div style="font-size: 0.875rem; margin: 0.25rem 0;">${file.name} (${formatFileSize(file.size)})</div>`
                ).join('')}
            </div>
            <button class="upload-btn" onclick="document.getElementById('batch-file-input').click()">重新选择</button>
        `;
    } else {
        uploadContent.innerHTML = `
            <i class="ri-upload-cloud-2-line upload-icon"></i>
            <h3>拖放多张图片到这里</h3>
            <p>或点击选择多个文件</p>
            <p class="file-types">支持格式：JPG、PNG、WebP、GIF（单张最大10MB，最多10张）</p>
            <input type="file" id="batch-file-input" accept="image/*" multiple hidden>
            <button class="upload-btn">选择图片</button>
        `;

        // 重新绑定事件
        const newInput = document.getElementById('batch-file-input');
        const newBtn = uploadContent.querySelector('.upload-btn');
        newBtn.addEventListener('click', () => newInput.click());
        newInput.addEventListener('change', handleBatchFileSelect);
    }
}

// 压缩单张图片
async function compressSingleImage() {
    if (!currentSingleFile) {
        showToast('请先选择图片', 'error');
        return;
    }

    showLoading(true);
    elements.singleCompressBtn.classList.add('loading');

    const formData = new FormData();
    formData.append('image', currentSingleFile);
    formData.append('quality', elements.qualitySlider.value);
    formData.append('format', elements.formatSelect.value);

    try {
        const response = await fetch('/api/compress', {
            method: 'POST',
            body: formData
        });

        const result = await response.json();

        if (result.success) {
            singleCompressedResult = result;
            displaySingleResult(result);
            showToast('图片压缩成功！', 'success');
        } else {
            showToast(result.error || '压缩失败', 'error');
        }
    } catch (error) {
        console.error('压缩错误:', error);
        showToast('压缩过程中出现错误', 'error');
    } finally {
        showLoading(false);
        elements.singleCompressBtn.classList.remove('loading');
    }
}

// 显示单张压缩结果
function displaySingleResult(result) {
    // 显示结果区域
    elements.singleResult.style.display = 'block';

    // 确保滑动对比功能已初始化
    setTimeout(() => {
        // 设置滑动对比的图片
        setupComparisonViews(result);

        // 等待图片加载后设置无缝对比
        setTimeout(() => {
            setupSeamlessComparison();
            // 重新初始化滑动对比功能，确保事件绑定正常
            initSliderComparison();
        }, 200);
    }, 100);

    // 设置下载链接
    elements.singleDownloadBtn.onclick = () => {
        const downloadUrl = `${result.compressedFile.url}?original=${encodeURIComponent(result.originalFile.name)}`;
        window.open(downloadUrl, '_blank');
    };
}

// 设置对比视图
function setupComparisonViews(result) {
    // 滑动对比元素
    const sliderOriginal = document.getElementById('slider-original');
    const sliderCompressed = document.getElementById('slider-compressed');
    const sliderOriginalSize = document.getElementById('slider-original-size');
    const sliderCompressedSize = document.getElementById('slider-compressed-size');
    const sliderCompressionRatio = document.getElementById('slider-compression-ratio');

    // 设置压缩后图片
    if (sliderCompressed) {
        sliderCompressed.src = result.compressedFile.url;
    }

    // 设置原始图片 - 使用文件读取器重新加载
    if (sliderOriginal && currentSingleFile) {
        const reader = new FileReader();
        reader.onload = (e) => {
            sliderOriginal.src = e.target.result;
        };
        reader.readAsDataURL(currentSingleFile);
    }

    // 设置信息文本
    if (sliderOriginalSize) sliderOriginalSize.textContent = result.originalFile.sizeFormatted;
    if (sliderCompressedSize) sliderCompressedSize.textContent = result.compressedFile.sizeFormatted;
    if (sliderCompressionRatio) sliderCompressionRatio.textContent = `${result.compressionRatio}%`;
}

// 初始化滑动对比功能
function initSliderComparison() {
    const sliderContainer = document.querySelector('.image-slider-wrapper');
    const sliderDivider = document.querySelector('.slider-divider');
    const sliderCompressed = document.getElementById('slider-compressed');

    if (!sliderContainer || !sliderDivider || !sliderCompressed) {
        console.error('滑动对比元素未找到:', { sliderContainer, sliderDivider, sliderCompressed });
        return;
    }

    // 初始化位置在中间
    updateSliderClipPath(50);
    sliderDivider.style.left = '50%';

    let isDragging = false;

    function handleMouseDown(e) {
        isDragging = true;
        e.preventDefault();
        sliderDivider.style.cursor = 'grabbing';
        console.log('开始拖拽');
    }

    function handleMouseMove(e) {
        if (!isDragging || !sliderContainer) return;

        const rect = sliderContainer.getBoundingClientRect();
        const x = e.clientX - rect.left;
        const percentage = Math.max(0, Math.min(100, (x / rect.width) * 100));

        updateSliderClipPath(percentage);
        sliderDivider.style.left = percentage + '%';
    }

    function handleMouseUp() {
        isDragging = false;
        if (sliderDivider) {
            sliderDivider.style.cursor = 'grab';
        }
        console.log('停止拖拽');
    }

    // 绑定事件
    sliderDivider.addEventListener('mousedown', handleMouseDown);
    document.addEventListener('mousemove', handleMouseMove);
    document.addEventListener('mouseup', handleMouseUp);

    // 触摸支持
    function handleTouchStart(e) {
        isDragging = true;
        e.preventDefault();
    }

    function handleTouchMove(e) {
        if (!isDragging || !sliderContainer) return;

        const touch = e.touches[0];
        const rect = sliderContainer.getBoundingClientRect();
        const x = touch.clientX - rect.left;
        const percentage = Math.max(0, Math.min(100, (x / rect.width) * 100));

        updateSliderClipPath(percentage);
        sliderDivider.style.left = percentage + '%';
    }

    function handleTouchEnd() {
        isDragging = false;
    }

    sliderDivider.addEventListener('touchstart', handleTouchStart);
    document.addEventListener('touchmove', handleTouchMove);
    document.addEventListener('touchend', handleTouchEnd);

    console.log('滑动对比功能已初始化');
}

// 更新滑动遮罩的裁剪路径
function updateSliderClipPath(percentage) {
    const sliderCompressed = document.getElementById('slider-compressed');
    if (!sliderCompressed) {
        console.error('压缩图片元素未找到');
        return;
    }

    // clip-path: inset(top right bottom left)
    // percentage是竖线的位置，左边显示压缩后的图片，右边显示原始图片
    // 所以压缩图片的显示区域是从0到percentage
    const rightClip = 100 - percentage;
    const clipPath = `inset(0 ${rightClip}% 0 0)`;
    sliderCompressed.style.clipPath = clipPath;

    console.log('更新clip-path:', { percentage, rightClip, clipPath });
}

// 确保图片尺寸一致的无缝对比
function setupSeamlessComparison() {
    const sliderOriginal = document.getElementById('slider-original');
    const sliderCompressed = document.getElementById('slider-compressed');

    if (!sliderOriginal || !sliderCompressed) return;

    // 等待图片加载完成
    Promise.all([
        new Promise(resolve => {
            if (sliderOriginal.complete) resolve();
            else sliderOriginal.onload = resolve;
        }),
        new Promise(resolve => {
            if (sliderCompressed.complete) resolve();
            else sliderCompressed.onload = resolve;
        })
    ]).then(() => {
        // 两张图片使用相同的样式，确保完全重叠
        // CSS已经设置了相同的尺寸和位置，这里只需要确保clip-path正确
        updateSliderClipPath(50); // 重置到中间位置
    });
}


// 压缩批量图片
async function compressBatchImages() {
    if (currentBatchFiles.length === 0) {
        showToast('请先选择图片', 'error');
        return;
    }

    showLoading(true);
    elements.batchCompressBtn.classList.add('loading');

    const formData = new FormData();
    currentBatchFiles.forEach(file => {
        formData.append('images', file);
    });
    formData.append('quality', elements.batchQuality.value);
    formData.append('format', elements.batchFormat.value);

    try {
        const response = await fetch('/api/batch-compress', {
            method: 'POST',
            body: formData
        });

        const result = await response.json();

        if (result.success) {
            batchCompressedResults = result.results.filter(r => !r.error);
            displayBatchResults();
            showToast(`成功压缩 ${batchCompressedResults.length} 张图片！`, 'success');
        } else {
            showToast(result.error || '批量压缩失败', 'error');
        }
    } catch (error) {
        console.error('批量压缩错误:', error);
        showToast('批量压缩过程中出现错误', 'error');
    } finally {
        showLoading(false);
        elements.batchCompressBtn.classList.remove('loading');
    }
}

// 显示批量压缩结果
function displayBatchResults() {
    // 计算统计信息
    let originalTotal = 0;
    let compressedTotal = 0;

    batchCompressedResults.forEach(result => {
        originalTotal += result.originalFile.size;
        compressedTotal += result.compressedFile.size;
    });

    const saved = originalTotal - compressedTotal;
    const savedPercentage = ((saved / originalTotal) * 100).toFixed(2);

    // 更新统计信息
    elements.batchOriginalTotal.textContent = formatFileSize(originalTotal);
    elements.batchCompressedTotal.textContent = formatFileSize(compressedTotal);
    elements.batchSaved.textContent = `${formatFileSize(saved)} (${savedPercentage}%)`;

    // 生成批量结果网格
    elements.batchGrid.innerHTML = batchCompressedResults.map(result => `
        <div class="batch-item">
            <img src="${result.compressedFile.url}" alt="${result.originalFile.name}">
            <div class="batch-item-info">
                <p><span>文件名:</span> <span>${result.originalFile.name}</span></p>
                <p><span>原始:</span> <span>${result.originalFile.sizeFormatted}</span></p>
                <p><span>压缩后:</span> <span>${result.compressedFile.sizeFormatted}</span></p>
                <p><span>分辨率:</span> <span>${result.compressedFile.width} × ${result.compressedFile.height}</span></p>
            </div>
            <div class="batch-item-ratio">压缩 ${result.compressionRatio}%</div>
            <button class="download-btn" onclick="window.open('${result.compressedFile.url}?original=${encodeURIComponent(result.originalFile.name)}', '_blank')">
                <i class="ri-download-2-line"></i>
                下载
            </button>
        </div>
    `).join('');

    // 设置下载所有图片按钮
    elements.downloadAllBtn.onclick = downloadAllImages;

    // 显示结果区域
    elements.batchResults.style.display = 'block';
}

// 下载所有图片
async function downloadAllImages() {
    if (batchCompressedResults.length === 0) {
        showToast('没有可下载的图片', 'error');
        return;
    }

    showToast('正在准备下载...', 'success');

    // 方式1: 尝试创建ZIP下载
    if (batchCompressedResults.length > 1) {
        try {
            await downloadAsZip();
        } catch (error) {
            console.log('ZIP下载失败，改用逐个下载:', error);
            downloadIndividually();
        }
    } else {
        // 只有一张图片时直接下载
        window.open(batchCompressedResults[0].compressedFile.url, '_blank');
    }
}

// 下载为ZIP文件
async function downloadAsZip() {
    // 检查浏览器是否支持 Streams API
    if (!window.stream || !window.Response) {
        throw new Error('浏览器不支持流式下载');
    }

    // 创建ZIP文件
    const zip = new JSZip();

    // 添加所有图片到ZIP
    for (let i = 0; i < batchCompressedResults.length; i++) {
        const result = batchCompressedResults[i];
        try {
            const response = await fetch(result.compressedFile.url);
            const blob = await response.blob();
            const fileName = getDownloadFileName(result.originalFile.name, result.compressedFile.name);
            zip.file(fileName, blob);
        } catch (error) {
            console.error(`添加文件到ZIP失败: ${result.originalFile.name}`, error);
        }
    }

    // 生成ZIP文件并下载
    const zipBlob = await zip.generateAsync({ type: 'blob' });
    const zipUrl = URL.createObjectURL(zipBlob);
    const link = document.createElement('a');
    link.href = zipUrl;
    link.download = `compressed_images_${Date.now()}.zip`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(zipUrl);

    showToast(`已打包下载 ${batchCompressedResults.length} 张图片`, 'success');
}

// 逐个下载
function downloadIndividually() {
    let downloadCount = 0;
    const total = batchCompressedResults.length;

    showToast(`开始下载 ${total} 张图片...`, 'success');

    // 逐个打开下载链接
    batchCompressedResults.forEach((result, index) => {
        setTimeout(() => {
            const link = document.createElement('a');
            link.href = `${result.compressedFile.url}?original=${encodeURIComponent(result.originalFile.name)}`;
            link.download = getDownloadFileName(result.originalFile.name, result.compressedFile.name);
            link.target = '_blank';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);

            downloadCount++;
            if (downloadCount === total) {
                showToast(`已下载 ${total} 张图片`, 'success');
            }
        }, index * 200); // 减少间隔到200ms
    });
}

// 获取下载文件名
function getDownloadFileName(originalName, compressedName) {
    const originalExt = originalName.split('.').pop().toLowerCase();
    const compressedExt = compressedName.split('.').pop().toLowerCase();

    // 如果格式相同，使用原文件名
    if (originalExt === compressedExt) {
        return originalName;
    }

    // 如果格式不同，修改扩展名
    const nameWithoutExt = originalName.substring(0, originalName.lastIndexOf('.'));
    return `${nameWithoutExt}.${compressedExt}`;
}

// 下载单张图片
function downloadSingleImage() {
    if (singleCompressedResult) {
        window.open(singleCompressedResult.compressedFile.url, '_blank');
    }
}

// 验证图片文件
function validateImageFile(file) {
    const validTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/webp', 'image/gif'];
    const maxSize = 10 * 1024 * 1024; // 10MB

    if (!validTypes.includes(file.type)) {
        showToast('不支持的文件格式，请选择JPG、PNG、WebP或GIF图片', 'error');
        return false;
    }

    if (file.size > maxSize) {
        showToast('文件大小超过10MB限制', 'error');
        return false;
    }

    return true;
}

// 更新预设按钮状态
function updatePresetButtons(quality) {
    elements.presetBtns.forEach(btn => {
        btn.classList.toggle('active', btn.dataset.quality === quality);
    });
}

// 更新批量预设按钮状态
function updateBatchPresetButtons(quality) {
    const batchPresetBtns = document.querySelectorAll('#batch-options .preset-btn');
    batchPresetBtns.forEach(btn => {
        btn.classList.toggle('active', btn.dataset.quality === quality);
    });
}

// 格式化文件大小
function formatFileSize(bytes) {
    if (bytes === 0) return '0 B';
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

// 显示/隐藏加载遮罩
function showLoading(show) {
    elements.loadingOverlay.classList.toggle('active', show);
}

// 显示Toast通知
function showToast(message, type = 'success') {
    const toast = elements.toast;
    const icons = {
        success: 'ri-checkbox-circle-line',
        error: 'ri-error-warning-line',
        warning: 'ri-alert-line'
    };

    toast.className = `toast ${type} show`;
    toast.innerHTML = `
        <i class="${icons[type]}"></i>
        <span>${message}</span>
    `;

    setTimeout(() => {
        toast.classList.remove('show');
    }, 3000);
}

// 工具函数：获取文件扩展名
function getFileExtension(filename) {
    return filename.slice((filename.lastIndexOf(".") - 1 >>> 0) + 2);
}

// 工具函数：生成随机文件名
function generateRandomFileName(originalName, format) {
    const timestamp = Date.now();
    const random = Math.random().toString(36).substr(2, 9);
    const name = originalName.split('.')[0];
    return `${name}_${timestamp}_${random}.${format}`;
}